package com.ruoyi.web.controller.supconauth;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.constant.ShiroConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quartz.task.SupconAuthTask;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/supcon")
public class SupconAuthController
{
    private static final Logger log = LoggerFactory.getLogger(SupconAuthController.class);
    
    private String prefix = "supconauth";
    
    public static String keystr = ":<xsd#$@ssfd<<-&";
    
    static int errorCount = 0;
    
    @CrossOrigin
    @GetMapping("getAuth")
    public String getAuth(HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
//    	String code = request.getParameter("a");
//    	String machineCode = request.getParameter("b");
//    	try {
//			machineCode = URLDecoder.decode( machineCode, "UTF-8" );
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//    	mmap.put("code", code);
//    	mmap.put("machineCode", machineCode);
        return prefix + "/getAuth";
    }
    
    @CrossOrigin
    @ResponseBody
    @PostMapping("getAuth")
    public AjaxResult getAuthData(@RequestParam("code") String code,@RequestParam("machineCode") String machineCode,
    		@RequestParam("exchangeCode") String exchangeCode,@RequestParam("shutdownOnly") String shutdownOnly) 
    				throws UnsupportedEncodingException
    {
    	AjaxResult result = AjaxResult.success();
    	code = code.trim();
    	machineCode = machineCode.trim();
    	exchangeCode = exchangeCode.trim();
    	shutdownOnly = shutdownOnly.trim();
    	
    	if (StringUtils.isEmpty(exchangeCode)) {
    		errorCount ++ ;
    		return AjaxResult.error();
		}
    	
    	if (!SupconAuthTask.exchangeCode.equals(exchangeCode)) {
    		if(errorCount > 20) {
    			result = AjaxResult.error();
    			result.put("msg", "系统已记录你的访问信息，包含IP、DNS、MAC等网络信息，将保留追究你法律责任的权力！");
    			return result;
    		}
    		errorCount ++ ;
    		result = AjaxResult.error();
    		result.put("msg", "F码验证错误！");
    		return result;
		}
    	
    	
    	errorCount = 0;
    	StringBuffer sb = new StringBuffer(machineCode);
        if ("1".equals(shutdownOnly) && sb.length()>64) {
	        sb.delete(0,32);
	        sb.delete(sb.length()-32,sb.length());
		}
        String desStr = code + sb.toString();
        
        String sign = Hex.encodeHexString( DesUtil.encryptByte(desStr.getBytes(ShiroConstants.ENCODING), keystr));
    	
    	result.put("sign", sign);
    	//将编码重新随机为空
    	//SupconAuthTask.exchangeCode = "";
    	
        return result;
    }
    
    @CrossOrigin
    @ResponseBody
    @GetMapping("getAuth2")
    public AjaxResult getAuthData2(HttpServletRequest req, HttpServletResponse resp) 
    				throws UnsupportedEncodingException
    {
    	String code = req.getParameter("code");
    	String machineCode = req.getParameter("machineCode");
    	String exchangeCode = req.getParameter("exchangeCode");
    	String shutdownOnly = req.getParameter("shutdownOnly");
        return getAuthData(code, machineCode, exchangeCode, shutdownOnly);
    }
    
    
    @GetMapping("getExchangeCode")
    public String getExchangeCode(HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
    	//如果大于500，默认为遭受到了攻击，就不再返回信息了
    	if(runThreadCount > 15) {
    		mmap.put("exchangeCode", "你特么违法了，你知道吗？");
    		return prefix + "/getExchangeCode";
    	}
    	mmap.put("exchangeCode", SupconAuthTask.exchangeCode);
    	
    	InitExchangeCodeThread thread = new InitExchangeCodeThread();
    	thread.start();
    	runThreadCount++;
        return prefix + "/getExchangeCode";
    }
    
    @GetMapping("getExchangeCode2")
    public String getExchangeCode2(HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
    	//如果大于500，默认为遭受到了攻击，就不再返回信息了
    	if(runThreadCount > 15) {
    		mmap.put("exchangeCode", "你特么违法了，你知道吗？");
    		return prefix + "/getExchangeCode";
    	}
    	SupconAuthTask.exchangeCode = SupconAuthTask.generateRandomCharacter();
    	mmap.put("exchangeCode", SupconAuthTask.exchangeCode);
    	
    	InitExchangeCodeThread thread = new InitExchangeCodeThread();
    	thread.start();
    	runThreadCount++;
        return prefix + "/getExchangeCode";
    }
    
    public static String generateRandomCharacter() {
        String characters = "1234567890";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }

        return sb.toString();
    }
    
    static int runThreadCount = 0;
    public class InitExchangeCodeThread extends Thread{
        @Override
        public void run() {
        	try {
				Thread.sleep(1000*60*1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	runThreadCount --;
        	//SupconAuthTask.exchangeCode = "";
        }
    }
    
}
